import flask
import json
import copy
import os.path
import logging
import KeepAccountServices
import URLBackup
from Common import *


path = os.path.abspath(__file__)
dirname, useless = os.path.split(path)
ROOT_DIR = dirname + '/'
CONF_DIR = ROOT_DIR + 'conf/'
LOG_DIR = ROOT_DIR + 'log/'
LOG_FILE_NAME = LOG_DIR + 'ka.log'

app = flask.Flask(__name__)
app.debug = True
url_backup = URLBackup.URLBackup()
services = KeepAccountServices.KeepAccountServices(app.logger)

@app.route('/')
def default_index():
    return flask.redirect('/home')

@app.route('/favicon.ico')
def favicon():
    return flask.send_file('web/favicon.ico')

@app.route('/<page_name>')
def get_page(page_name):
    file_name = 'web/' + page_name + '.html'
    if os.path.exists(file_name) == False:
        flask.abort(404)
    return flask.send_file(file_name)

@app.route('/res/<file_name>')
def get_resource(file_name):
    return flask.send_file('web/' + file_name)

@app.route('/service/<service_name>/<method_name>')
def handle_service(service_name, method_name):
    args = flask.request.args.to_dict()
    ori_args = copy.deepcopy(args)
    ret = services.handleRequest(service_name, method_name, args)
    if ret['errno'] == Error.SUCCESS:
        url_backup.backup(service_name, method_name, ori_args)
    else:
        app.logger.warning('req failed! service:' + service_name + ' method:' + method_name + ' args:' + json.dumps(ori_args))
    return json.dumps(ret)

@app.route('/backup')
def backup():
    if os.path.exists('data/commit.backup'):
        return flask.send_file('data/commit.backup')
    return makeReturn(Error.FILE_NOT_EXIST)

if __name__ == '__main__':
    handler = logging.FileHandler(LOG_FILE_NAME)
    handler.setLevel(logging.DEBUG)
    logging_format = logging.Formatter(
        '%(asctime)s %(levelname)s %(filename)s %(lineno)s %(message)s')
    handler.setFormatter(logging_format)
    app.logger.addHandler(handler)
    app.logger.info('KeepAccount start.')
    app.run(host='0.0.0.0')
    app.logger.info('KeepAccount exit.')
